package com.io.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.io.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * The class/interface 自动注入指定字段
 *
 * @author guodd
 * @version 1.0 use jdk 1.8
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 创建时间
     */
    private static final String FIELD_SYS_CREATE_DATE = "createDate";
    /**
     * 修改时间
     */
    private static final String FIELD_SYS_UPDATE_DATE = "updateDate";
    /**
     * 用户ID
     */
    private static final String FIELD_SYS_USER_ID = "userId";
    /**
     * 部门ID
     */
    private static final String FIELD_SYS_DEPT_ID = "deptId";

    @Override
    public void insertFill(MetaObject metaObject) {
        // 判断表中是否用字段如果没有就不处理
        boolean isOpt = metaObject.hasSetter(FIELD_SYS_CREATE_DATE);
        if (isOpt) {
            // 获取数据
            Long deptId = BaseController.getDeptId();
            Long userId = BaseController.getUserId();
            if (metaObject.hasGetter(FIELD_SYS_CREATE_DATE)) {
                this.setFieldValByName(FIELD_SYS_CREATE_DATE, LocalDateTime.now(), metaObject);
                this.setFieldValByName(FIELD_SYS_UPDATE_DATE, LocalDateTime.now(), metaObject);
            }

            // 保存系统用户
            if (metaObject.hasGetter(FIELD_SYS_USER_ID)) {
                this.setFieldValByName(FIELD_SYS_USER_ID, userId, metaObject);
            }

            // 保存部门
            if (metaObject.hasGetter(FIELD_SYS_DEPT_ID)) {
                this.setFieldValByName(FIELD_SYS_DEPT_ID, deptId, metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 判断表中是否用字段如果没有就不处理
        boolean isOpt = metaObject.hasSetter(FIELD_SYS_CREATE_DATE);
        if (isOpt) {
            if (metaObject.hasGetter(FIELD_SYS_UPDATE_DATE)) {
                this.setFieldValByName(FIELD_SYS_UPDATE_DATE, LocalDateTime.now(), metaObject);
            }
        }
    }
}
